package com.tensquare.article.service;

import com.tensquare.article.pojo.Comment;
import com.tensquare.article.repository.CommentRepository;
import com.tensquare.util.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class CommentService {

    @Autowired
    private CommentRepository commentRepository;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private MongoTemplate mongoTemplate;

    public List<Comment> findAll() {
        List<Comment> all = commentRepository.findAll();
        return all;
    }

    public Comment findById(String commentId) {
        Comment comment = commentRepository.findById(commentId).get();
        return comment;
    }

    public void save(Comment comment) {
        //生成分布式唯一ID
        String _id = idWorker.nextId()+"";
        comment.set_id(_id);
        //初始化信息
        comment.setThumbup(0);
        comment.setPublishdate(new Date());
        commentRepository.save(comment);
    }

    public void deleteById(String commentId) {
        commentRepository.deleteById(commentId);
    }

    public boolean updateById(String commentId, Comment comment) {
        //首先判断下这个ID是否存在
        List<Comment> comments = commentRepository.findAll();
        boolean flag = false;
        for(Comment c:comments){
            if(c.get_id().equals(commentId)){
                flag = true;
                break;
            }
        }
        if(flag){ //说明ID存在，则允许修改
            comment.set_id(commentId);
            commentRepository.save(comment);
            return true;
        }
        return false;

    }

    public void thumbup(String commentId, Comment comment) {
        //封装查询条件
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(commentId));
        Update update = new Update();
        update.inc("thumbup");
        //第一个参数是修改的条件
        //第二个参数是修改的数值
        //第三个参数是集合的名称
        mongoTemplate.updateFirst(query,update,"comment");
    }
}
